package org.lecric.wind44.server.model;

import java.lang.reflect.InvocationTargetException;
import java.util.Date;

import org.apache.commons.beanutils.BeanUtils;
import org.lecric.wind44.client.model.Post;
import org.lecric.wind44.client.model.Spot;
import org.lecric.wind44.client.model.SpotInformation;
import org.lecric.wind44.client.model.UserInfo;

import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserServiceFactory;

public class DBUtil
{
	public static Spot db2pojo(DBSpot dbSpot) {
		return new Spot(dbSpot.getId(),
				dbSpot.getName(),
				dbSpot.isPub(),
				toString(dbSpot.getAuthor()),
				dbSpot.getLatitude(),
				dbSpot.getLongitude(),
				dbSpot.getOrder());
	}

	public static String toString(User user) {
		if(user!=null)
			return user.getNickname();
		else
			return null;
	}

	public static SpotInformation db2pojo(DBSpotInfo dbSpotInfo) {
		return new SpotInformation(dbSpotInfo.getId(),
				dbSpotInfo.getName(),
				dbSpotInfo.getUrl(),
				dbSpotInfo.isPub(),
				toString(dbSpotInfo.getAuthor()),
				dbSpotInfo.getOrder());
	}

	public static DBSpotInfo pojo2db(SpotInformation spotInformation, long spotId)
	{
		return new DBSpotInfo(UserServiceFactory.getUserService().getCurrentUser(), spotInformation.getName(), spotInformation.getUrl(),
				new Date(), spotInformation.isPub(), spotId, spotInformation.getOrder());
	}

	public static DBSpot pojo2db(Spot spot)
	{
		return new DBSpot(UserServiceFactory.getUserService().getCurrentUser(),
				spot.getName(), new Date(), spot.isPub(), spot.getLatitude(),
				spot.getLongitude(),
				spot.getOrder());
	}

	public static UserInfo db2pojo(DBUserInfo userInfo)
	{
		UserInfo result = new UserInfo();
		try
		{
			BeanUtils.copyProperties(result, userInfo);
		}
		catch (IllegalAccessException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		catch (InvocationTargetException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return result;
	}

	public static Post db2pojo(DBPost dbPost)
	{
		Post post=new Post();
//		post.setDate(dbPost.getDate());
//		post.setSpot(dbPost.getSpot());
//		post.setMessage(dbPost.getMessage());
		try
		{
			BeanUtils.copyProperties(post, dbPost);
		}
		catch (IllegalAccessException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		catch (InvocationTargetException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return post;
	}

	public static DBPost pojo2db(Post post) {
		DBPost dbPost=new DBPost();
		try
		{
			BeanUtils.copyProperties(dbPost, post);
		}
		catch (IllegalAccessException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		catch (InvocationTargetException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return dbPost;
	}
}
